from adbutils import adb

from conf_phone import get_device_name


def select_phone():
    """
    选择手机，
    :return:
    """
    while True:
        num = 0
        devices_list = adb.device_list()
        if not devices_list:
            input("No devices connected.输入任意字符重新获取：")
            continue
        for d in devices_list:
            device_name = get_device_name(d)
            # 0 | 荣耀Play7T | A3QU9X3608W04445
            print(f"{num} | {device_name} | {d.serial}")
            num += 1

        option = input("请输入需要连接的手机序号：")
        if option.isdigit() and int(option) <= num:
            option = int(option)
            break
        else:
            print("输入的字符不对，重新输入")
    device = devices_list[option]
    is_connected(device)
    serialno = device.serial
    device_name = get_device_name(device)
    return serialno, device_name


def is_connected(device):
    # 检查手机是否联网，
    ok = False
    while not ok:
        # 执行 ping 命令检查网络连接
        try:
            output = device.shell('ping -c 4 223.5.5.5')  # 阿里 Ali DNS
            if '64 bytes from' in output:
                print("设备已联网。")
                ok = True
            else:
                print("设备未联网，无法访问外部地址。")
                input("检查手机联网设置，输入任意字符继续：")
        except Exception as e:
            print("检查网络连接时出错：", e)


if __name__ == '__main__':
    pass
